<?php

namespace app\admin\controller\vv;

use app\common\controller\Backend;
use think\Validate;
use vv\model\Admin;
use vv\model\Shop;

class Bill extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model          = new \vv\model\Bill();
        $this->relationSearch = true;
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if (!$this->request->isAjax()) {
            return $this->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->with([
            'admin',
            'shop'
        ])->where($where)->order($sort, $order)->paginate($limit);
        return json([
            'total' => $list->total(),
            'rows'  => $list->items()
        ]);
    }

    public function add()
    {
        if (!$this->request->isPost()) {
            return $this->fetch();
        }
        $params = $this->request->post('row/a');
        $this->check($params);
        $this->model->save($params);
        $this->success();
    }

    private function check($params)
    {
        $validate = new Validate([
            'shop_id|供应商'      => 'require',
            'type|类型'           => 'require',
            'title|发票抬头'      => 'require',
            'name|个人或单位名称' => 'require',
            'content|发票内容'    => 'require',
            'quota|发票金额'      => 'require',
            'mobile|收票人手机'   => 'require|regex:1\d{10}',
            'email|收票人邮箱'    => 'require|email',
        ]);
        $validate->check($params) || $this->error($validate->getError());
    }
}